package me.pplay.playtalk.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import me.pplay.playtalk.bean.Chat;
import me.pplay.playtalk.bean.ChattingRecord;
import me.pplay.playtalk.bean.NotificationEntity;
import me.pplay.playtalk.data.Globals;
import me.pplay.playtalk.database.ChatListDb;
import me.pplay.playtalk.database.FriendDb;
import me.pplay.playtalk.database.NotificationDb;
import me.pplay.playtalk.protocol.ProtocolType;
import me.pplay.playtalk.protocol.TpChat;
import me.pplay.playtalk.protocol.TpChatRoom;
import me.pplay.playtalk.protocol.bean.RspData;
import me.pplay.playtalk.protocol.bean.TPBuddyinfo;
import me.pplay.playtalk.protocol.bean.TpGroup;
import me.pplay.playtalk.protocol.bean.TpNotiNode;
import me.pplay.playtalk.protocol.bean.TpNotiNode.tp_msg_node;
import me.pplay.playtalk.protocol.bean.TpNotiNode.tp_req_node;
import me.pplay.playtalk.protocol.bean.TpNotiNode.tp_res_node;
import me.pplay.playtalk.util.BuddyInfoUtil;
import me.pplay.playtalk.util.LogManager;
import me.pplay.playtalk.util.fileUtil.ChattingRecordFile;
import me.pplay.playtalk.util.fileUtil.MediaFile;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

public class PlayTalkService extends Service {
	

	public static final String MESSAGE_CHATLIST_BRODCASE 	= "me.pplay.playtalk.message_chatlist";
	public static final String MESSAGE_CHAT_BRODCASE		= "me.pplay.playtalk.message_chat";
	public static final String COMMUNITY_CHATRLIST_BRODCASE	= "me.pplay.playtalk.community_chatlist";
	public static final String COMMUNITY_CHAT_BRODCASE		= "me.pplay.playtalk.community_chat";
	
	public static final int NOTIFY_ID = 0;
	
	static PlayTalkService playTalkService;
		
//	private NotificationManager notificationManager;
//	private Notification mNotification;
	
	/**
	 * tongzhi
	 */
	private TpGroup tpGroup = null;
	private int skyId 		= -2;
	private Handler handler; 
	private MyBroadcaseReceiver receiver;
	private ChatListDb dbChat;
	private FriendDb friendDb;
	private NotificationDb dbNoti;
	public boolean isMessage = false;
	public boolean isNotificaiton = false;
	public boolean isDiscover = false;

	@Override
	public void onCreate() {
		super.onCreate();
		LogManager.LogShow("PlayTalkService", "oncreate", LogManager.INFO);
		playTalkService	= this;
		receiver			= new MyBroadcaseReceiver();
		IntentFilter filter = new IntentFilter(PlayTalkService.MESSAGE_CHAT_BRODCASE);
		registerReceiver(receiver, filter);
	}
	
	public Handler serviceHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Intent intent  = new Intent();
			LogManager.LogShow("PalyTalkService", "PalyTalkService msg.what:"+msg.what);
			intent.setAction(MESSAGE_CHAT_BRODCASE);
			intent.putExtras(msg.getData());
			sendBroadcast(intent);
//			switch (msg.what) {
//				case TpChat.CHAT_ROOM_GETLIST_OK:	//聊天室列表
//					intent.setAction(COMMUNITY_CHATRLIST_BRODCASE);
//					break;
//				case TpChatRoom.CHATROOM_MSG_OK:
//					intent.setAction(COMMUNITY_CHAT_BRODCASE);
//					break;
//				case TpChat.CHAT_NOTIFICATION_OK:
//					intent.setAction(MESSAGE_CHAT_BRODCASE);
//					break;
//				case TpChat.CHAT_GETBUDDIES_OK:	//好友列表
//					intent.setAction(MESSAGE_CHATLIST_BRODCASE);
//					break;
//			}
			
		}
	};



//	private void dispalyNotificationManager(){
//		if(notificationManager == null)
//			notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//		if(mNotification == null){
//			mNotification	= new Notification(R.drawable.ic_launcher, "notification", System.currentTimeMillis());
////			mNotification.defaults 	|= Notification.DEFAULT_LIGHTS; //LED灯光提醒
//			mNotification.flags 	|= Notification.FLAG_AUTO_CANCEL;
//		}
//		PendingIntent pendingIntent  = PendingIntent.getActivity(this, 0, new Intent(this, SignInActivity.class), 0);
//		mNotification.setLatestEventInfo(this, "message", "message content", pendingIntent);
//		notificationManager.notify(NOTIFY_ID, mNotification);
//	}

	
	public void setDD(){
		
	}
	
	public static PlayTalkService getInstance() {
        return playTalkService;  
    } 
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	
	
	public void setValues(TpGroup tpGroup, int skyId){
		this.tpGroup	= tpGroup;
		this.skyId		= skyId;
	}
	
	public void setIsMessage(boolean bool){
		isMessage		= bool;
	}

	public void setHandler(Handler handler){
		this.handler	= handler;
	}
	
	public void setIsNotification(boolean bool){
		isNotificaiton	= bool;
	}
	
	public void setIsDiscover(boolean bool){
		isDiscover		= bool;
	}
	
	class MyBroadcaseReceiver extends BroadcastReceiver{
		
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundle   		= intent.getExtras();
			int typeFrom			= bundle.getInt("result");
			Object  resultdata		= (Object)bundle.getSerializable("resultdata");
			if(resultdata == null) return;
			int type 				= ((RspData)resultdata).getSubid();
			LogManager.LogShow("BroadcastReceiver", "MyBroadcaseReceiver typeFrom:"+typeFrom +"  noti_node.type:"+type);
			Object obj				= bundle.getSerializable("object");
			if(typeFrom == TpChat.CHAT_NOTIFICATION_OK || typeFrom == TpChatRoom.CHATROOM_MSG_OK){
				TpNotiNode noti_node 	= (TpNotiNode)obj;
				if(noti_node == null) return;
				ChattingRecord record  	= null;	
				int chat_record_type 	= -1;
				int int_chat_save		= 0;  // 1:页面刷新   2：数据库保存
				int friendRequsetType   = 0;
				
				switch (type) {
				case ProtocolType.ChatRoomType.TP_SUBSERVICE_CHATROOM_MSG: //聊天室
				case ProtocolType.NotiType.TP_NOTIFICATION_CHAT_MSG:		//点对点
				case ProtocolType.NotiType.TP_NOTIFICATION_CONFERENECT_MSG: //群消息
					tp_msg_node msg_node	= noti_node.getMsg_node();
					if(msg_node == null)return;
					if(type == ProtocolType.ChatRoomType.TP_SUBSERVICE_CHATROOM_MSG){
						if(tpGroup == null || tpGroup.getId() != msg_node.getGid())return;
						record = new ChattingRecord(msg_node.getGid(),msg_node.getAlias(), null, "0", msg_node.getMsg(), String.valueOf(System.currentTimeMillis()));
	//					ChattingRecordFile.saveChattingRecodToFile(record);
						setHandler(Globals.SETADAPTER,record);
						return;
					}else{
						chat_record_type 		= 0;
						int skyid_noti			= msg_node.getSkyid();
						int_chat_save 			= (skyId == msg_node.getSkyid() || skyId == msg_node.getGid()) ? 1 : 2;
						if(type == ProtocolType.NotiType.TP_NOTIFICATION_CONFERENECT_MSG){
							skyid_noti			= msg_node.getGid();
							chat_record_type	= 5;
						}
						System.out.println("消息  skyId：："+skyId + "   "+   chat_record_type+ "  msg_node skyid:"+int_chat_save);
						record = new ChattingRecord(skyid_noti, msg_node.getAlias(), null, "0", msg_node.getMsg(), String.valueOf(System.currentTimeMillis()));
					}
					break;
				case ProtocolType.NotiType.TP_NOTIFICATION_CHAT_DOWNLOADRES: //有资源文件
					tp_res_node res_node = noti_node.getRes_node();
					if(res_node != null){
						String fileType = MediaFile.fileType(res_node.getFilename()); //1:图片  2：视频  3：语音
						int_chat_save 	= (skyId == res_node.getSkyid() || skyId == res_node.getGoup_id()) ? 1 : 2;
						int skyid_noti	= res_node.getSkyid();
						chat_record_type = 0;
						if(res_node.getGoup_id() != -1){
							chat_record_type = 5;
							skyid_noti		 = res_node.getGoup_id();
						}
						System.out.println("download  skyId：："+res_node.getSkyid() + "   "+   res_node.getGoup_id()+ "  fileType:"+fileType + "   fileName::"+res_node.getFilename() +"  ::"+res_node.getFpath());
						record	= new ChattingRecord(res_node.getSkyid(), res_node.getAlias(), null, fileType, res_node.getIpath(), String.valueOf(System.currentTimeMillis()), res_node.getFilelen(), res_node.getFilename(), res_node.getFpath(), res_node.getServer_id());
					}
					break;
				case ProtocolType.NotiType.TP_NOTIFICATION_TEXT://系统公告
					String notificationStr = noti_node.getText();//系统公告
					System.out.println("TP_NOTIFICATION_TEXT"+notificationStr);
					if(dbNoti == null)
						dbNoti = new NotificationDb(context);
					dbNoti.add(new NotificationEntity(0, notificationStr, String.valueOf(System.currentTimeMillis())));
					if(isNotificaiton)
						setHandler(Globals.SETADAPTER, null);
	//					notificationValue	= msg_node.getAlias() + ":"+notificationStr;
	//					handler.sendEmptyMessage(DISPLAYNOTIFICATION);
						//添加到数据库  返回到Message界面时提示未读消息
					break;
				case ProtocolType.NotiType.TP_NOTIFICATION_CHAT_PREMITED:   //同意
					 friendRequsetType = 1;
				case ProtocolType.NotiType.TP_NOTIFICATION_CHAT_DENIED:		//拒绝
					 if(friendRequsetType != 0)  friendRequsetType = 2;
				case ProtocolType.NotiType.TP_NOTIFICATION_CHAT_BUDDYREQ:	//请求加好友
					if(friendRequsetType != 0)  friendRequsetType = 3;
				case ProtocolType.NotiType.TP_NOTIFICATION_CHAT_BSTATUS: 	//好友状态（上下线）
					if(friendRequsetType != 0)  friendRequsetType = 4;
					tp_req_node req_node = noti_node.getReq_node();
					if(req_node == null) return;
					TPBuddyinfo binfo = req_node.getBuddy();
					Chat chat = new Chat(friendRequsetType, binfo.getSkyid(), binfo.getAvatar_fpath(), BuddyInfoUtil.getAlias(binfo), req_node.getText(), String.valueOf(System.currentTimeMillis()));
					if(friendDb == null)
						friendDb = new FriendDb(PlayTalkService.this);
					friendDb.add(chat);
					if((isMessage  && friendRequsetType == 1)||(friendRequsetType == 2 && isNotificaiton) ||(isDiscover && friendRequsetType == 3))
						setHandler(Globals.SETADAPTER, null);
					break;
				}
				
				
				if(record == null)return;
				ChattingRecordFile.saveChattingRecodToFile(record, record.skyid);
				if(int_chat_save == 1){ //当前会话 通知当前界面更新数据
					setHandler(Globals.SETADAPTER, record);
					
				}else if(int_chat_save == 2){
					if(dbChat == null)
						dbChat	= new ChatListDb(PlayTalkService.this);
					Chat chat = dbChat.query(record.skyid);
					if(chat == null){
						chat	= new Chat(chat_record_type, record.skyid, record.name);
						chat.setCount(1);
						dbChat.add(chat);
					}else{
						chat.setCount(chat.getCount() + 1);
						dbChat.update(chat);
					}
					
					if(isMessage){ //Message界面 更改界面通知
						setHandler(Globals.SETMESSAGE_CHANGE, null);
					}
				}
			}else if(typeFrom == TpChat.CHAT_GETCONFERENCEGROUP_OK){
				if(type == ProtocolType.ChatType.TP_SUBSERVICE_CONFERENCE_GETGROUP){ // 群列表
					Map<TpGroup, List<TPBuddyinfo>> groupMap = (Map<TpGroup, List<TPBuddyinfo>>)obj;
					Globals.groupList.clear();
					List<Chat> groupList	= new ArrayList<Chat>();
					Iterator iterator 		= groupMap.keySet().iterator();
					while(iterator.hasNext()){
						TpGroup tpGroupItem = (TpGroup)iterator.next();
						if(tpGroupItem == null)
							return;
						Chat chat	= new Chat();
						System.out.println("exit.....id::"+tpGroupItem.getId() + "   "+tpGroupItem.getAlias() + "   "+tpGroupItem.getName() );
						String groupName = tpGroupItem.getName();
						chat.setSkyid(tpGroupItem.getId());
						chat.setName(groupName);
						chat.setTime(null);
						chat.setType(5);
						if(tpGroup != null && groupName != null && tpGroupItem.getId() == skyId && !groupName.equals(tpGroup.getName())) //创建新会话时，通知更改群名
							setHandler(Globals.SETTING_NEW_CONFERENCE_NAME, tpGroupItem.getName());
						
//						if(isMessage)
							groupList.add(chat);
//						else
							Globals.groupList.add(chat);
					}
					if(isMessage){
						setHandler(Globals.SETMESSAGE_GROUP_CHANGE, groupList);
					}
				}
			}else if(typeFrom == TpChat.CHAT_ROOM_GETLIST_OK){
				if(handler != null)
					handler.sendEmptyMessage(typeFrom);
			}
		}
		
	}
	
	private void setHandler(int what, Object obj){
		System.out.println("xiaoxi......"+handler);
		if(handler == null) return;
		Message msg = new Message();
		msg.what    = what;
		if(obj != null){
			Bundle bundle = new Bundle();
			bundle.putSerializable("obj", (Serializable)obj);
			msg.setData(bundle);
		}
		handler.sendMessage(msg);
	}
	
	@Override
	public void onDestroy() {
		LogManager.LogShow("PlayTalkService", "onDestroy", LogManager.INFO);
		unregisterReceiver(receiver);
		super.onDestroy();
	}
	
}
